#coding:utf8
import cherrypy
import datetime
import os
from ConnectMSSQL import ms

from head import *
from menu import *
from end import *

from utf8code import *
from xxtj import *

_js = """
        <script type="text/javascript">
            var rybh;
            $(function()
            {

                $(".class_tr td #updatebut").hide();

                //点一个部门进行查询
                $('.class_tr td a').click(function()
                {
                    window.location.href="/zzjg/serchRY?cxtj=" + $(this).text();
                });
                
                //高亮显示
                $(".table tr").hover
                (
                    function() { $(this).addClass("highlight"); },
                    function() { $(this).removeClass("highlight"); }
                );
                
                //单选框默认选中.变色.
                $('.table input[type="radio"]:checked').parents('tr').addClass('selected');
                
                //单击
                $('.table tr').click(function()
                {
                    $(this).siblings().removeClass('selected');
                    $(this).addClass('selected');
                    $(this).find('input[type="radio"]').attr('checked', 'checked');
                    rybh=$(this).find('td[id="1"]').text();
                });
                
                $(".class_tr td #delbut").click(function()
                {
                    $(this).parents('tr').siblings().removeClass('selected');
                    $(this).parents('tr').addClass('selected');
                    $(this).parents('tr').find('input[type="radio"]').attr('checked', 'checked');
                    rybh=$(this).parents('tr').find('td[id="1"]').text();
                    if(rybh)
                    {
                        var ret=confirm("确定删除编号为:" + rybh + "的人员?此操作不可恢复!请谨慎操作!")
                        if(ret == false)
                            return;
                        else
                            //ajax为删除做检验，已变更的人员不可删除，不然会造成数据库错误
                            var xmlhttp;
                            if (window.XMLHttpRequest)
                            {// code for IE7+, Firefox, Chrome, Opera, Safari
                              xmlhttp=new XMLHttpRequest();
                            }
                            else
                            {// code for IE6, IE5
                              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                            }
                        
                            xmlhttp.onreadystatechange=function()
                            {
                              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                                {
                                    if(xmlhttp.responseText == "no")
                                    {
                                        alert("删除失败!-_-|| 该人员已产生变更记录,不可删除!");
                                    }
                                    else
                                    {
                                        alert("删除成功!*^_^*");
                                        location.reload();
                                    }
                                }
                            }
                            xmlhttp.open("GET","/zzjg/delRY?rybh="+rybh,true);
                            xmlhttp.send();
                    }
                    else
                        alert("请选择人员");
                });
                
                $("#outbut").click(function()
                {
                    window.open("/zzjg/outRY");
                });
				
                $("#savebut").click(function()
                {
                    var gs,bm,zw,ry,bz,url;
                    gs = $(".class_tr td #gstext").attr("value");
                    bm = $(".class_tr td #bmtext").attr("value");
                    zw = $(".class_tr td #zwtext").attr("value");
                    ry = $(".class_tr td #rytext").attr("value");
                    bz = $(".class_tr td #bztext").attr("value");
                    url = "/zzjg/saveRY?gs="+gs +"&bm="+bm +"&zw="+zw +"&ry="+ry +"&bz="+bz;
                    var xmlhttp;
                    if (window.XMLHttpRequest)
                    {// code for IE7+, Firefox, Chrome, Opera, Safari
                      xmlhttp=new XMLHttpRequest();
                    }
                    else
                    {// code for IE6, IE5
                      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                
                    xmlhttp.onreadystatechange=function()
                    {
                      if (xmlhttp.readyState==4 && xmlhttp.status==200)
                        {
                            if(xmlhttp.responseText)
                            {
                                alert(xmlhttp.responseText);
                            }
                            if(xmlhttp.responseText == "保存成功!*^_^*")
                            {
                                location.reload();
                            }
                        }
                    }
                    xmlhttp.open("GET",url,true);
                    xmlhttp.send();
                });
                

                var zw,xm,bz;//全局的“职位”，“姓名”，“备注”变量
                $(".class_tr td #editbut").click(function()
                {
                    $(this).parents('tr').siblings().removeClass('selected');
                    $(this).parents('tr').addClass('selected');
                    $(this).parents('tr').find('input[type="radio"]').attr('checked', 'checked');
                    rybh=$(this).parents('tr').find('td[id="1"]').text();
                    if(rybh)
                    {
                        //显示更新按钮
                        $(this).parents('tr').find('input[id="updatebut"]').show();
                        //获取“职位”，“姓名”，“备注”值
                        zw = $(this).parents('tr').find('td[id="4"]').text();
                        xm = $(this).parents('tr').find('td[id="5"]').text();
                        bz = $(this).parents('tr').find('td[id="6"]').text();
                        //将“职位”，“姓名”，“备注”的值放到文本框里
                        $(this).parents('tr').find('td[id="4"]').html('<input type="text" id="zw_upt_text" value="'+zw+'" />');
                        $(this).parents('tr').find('td[id="5"]').html('<input type="text" id="xm_upt_text" value="'+xm+'" />');
                        $(this).parents('tr').find('td[id="6"]').html('<input type="text" id="bz_upt_text" value="'+bz+'" />');
                    }
                    else
                        alert("请选择人员");
                });

                $(".class_tr td #updatebut").click(function()
                {
                    $(this).parents('tr').siblings().removeClass('selected');
                    $(this).parents('tr').addClass('selected');
                    $(this).parents('tr').find('input[type="radio"]').attr('checked', 'checked');
                    rybh=$(this).parents('tr').find('td[id="1"]').text();
                    var zwtext=$("#zw_upt_text").val();
                    var xmtext=$("#xm_upt_text").val();
                    var bztext=$("#bz_upt_text").val();
                    if(zwtext==zw && xmtext==xm && bztext==bz)
                    {
                        alert("无需更新的内容!");
                        location.reload();
                    }

                    if(rybh&&xmtext)
                    {
                        var xmlhttp;
                        if (window.XMLHttpRequest)
                          xmlhttp=new XMLHttpRequest();
                        else
                          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    
                        xmlhttp.onreadystatechange=function()
                        {
                          if (xmlhttp.readyState==4 && xmlhttp.status==200)
                            {
                                if(xmlhttp.responseText == "no")
                                {
                                    alert("更新失败!-_-|| !");
                                }
                                else
                                {
                                    alert("更新成功!*^_^*");
                                    location.reload();
                                }
                            }
                        }
                        xmlhttp.open("GET","/zzjg/updateRY?rybh="+rybh+"&zw="+zwtext+"&xm="+xmtext+"&bz="+bztext,true);
                        xmlhttp.send();
                    }
                    else
                        alert("请选择人员,且姓名不能为空!");
                });
            });
        </script>
        """
_js_showInfo = """
    <script type="text/javascript">
      function showAndHide(obj,types){
        var Layer=window.document.getElementById(obj);
        switch(types){
          case "show":
            Layer.style.display="block";
          break;
          case "hide":
            Layer.style.display="none";
          break;
        }
      }
      function getValue(obj,str){
        var input=window.document.getElementById(obj);
        input.value=str;
      }
    </script>
"""
_js_noadmin = """
        <script type="text/javascript">
            $(function()
            {
                $('input[value="保存"]').hide();
                $('input[value="取消"]').hide();
                $('input[value="删除"]').hide();

                $('input[value="编辑"]').hide();
            });
        </script>
"""
_top = """
    <form method="get" action="/zzjg/serchRY">
        <div id="div_operate">
                                查询条件：
            <input type="text" id="serchtext" name="cxtj" onfocus="hidevalue()" placeholder="公司、部门、职位、姓名或备注" />
            <input type="submit" id="serchbut" value="查询" />
            <input type="button" id="outbut" value="导出全部人员" />
            <input type="button" id="exitbut" onclick="exit()" value="关闭" />
        </div>        
        <div id="div_data">
            <table width="auto" class="table">
              <tr class="class_tr_th">
                <th class="class_th" scope="col">√</th>
                <th class="class_th" scope="col">序号</th>
                <th class="class_th" scope="col">人员编号↑</th>
                <th class="class_th" scope="col">公司</th>
                <th class="class_th" scope="col">部门</th>
                <th class="class_th" scope="col">职位</th>
                <th class="class_th" scope="col">姓名</th>
                <th class="class_th" scope="col">备注</th>
                <th class="class_th" scope="col" id="id_th_opt">操作</th>
              </tr>
              <tr class="class_tr">
                <td><input type="radio" id="select" name="selradio" /></td>
                <td>0</td>
                <td><font>保存后自动生成</font></td>
                <td>
                    <input type="text" id="gstext" onfocus="showAndHide('ListGS','show');" onblur="showAndHide('ListGS','hide');"  />
                    <div class="MenuInfo" id="ListGS">
                            <ul>
                                %s
                            </ul>
                    </div>
                </td>
                <td>
                    <input type="text" id="bmtext" onfocus="showAndHide('List_BM','show');" onblur="showAndHide('List_BM','hide');" />
                    <div class="MenuInfo" id="List_BM">
                            <ul>
                                %s
                            </ul>
                    </div>
                </td>
                <td>
                    <input type="text" id="zwtext" onfocus="showAndHide('List_ZW','show');" onblur="showAndHide('List_ZW','hide');" />
                    <div class="MenuInfo" id="List_ZW">
                            <ul>
                                %s
                            </ul>
                    </div>
                </td>
                <td>
                    <input type="text" id="rytext" />
                </td>
                <td>
                    <input type="text" id="bztext" />
                </td>
                <td class="class_td_opt">
                    <input type="button" id="savebut" value="保存" />
                    <input type="reset" id="quitbut" value="取消" />
                </td>
              </tr>
          """
           
_end = """
            </table>
        </div>
    </form>
"""

class ZZJG:
    _mid_init = """            
    <tr class="class_tr">
        <td><input type="radio" id="select" name="selradio" /></td>
        <td>%s</td>
        <td id="%s">%s</td>
        <td>%s</td>
        <td><a href="javascript:void(0);">%s</a></td>
        <td id="%s">%s</td>
        <td id="%s">%s</td>
        <td id="%s">%s</td>
        <td class="class_td_opt">
            <input type="button" id="editbut" value="编辑" />
            <input type="button" id="updatebut" value="更新" />
            <input type="button" id="delbut" value="删除" />
        </td>
    </tr>
    """
    li_gs = """<li onmousedown="getValue('gstext',this.innerText);showAndHide('ListGS','hide');">%s</li>"""
    li_bm = """<li onmousedown="getValue('bmtext',this.innerText);showAndHide('List_BM','hide');">%s</li>"""
    li_zw = """<li onmousedown="getValue('zwtext',this.innerText);showAndHide('List_ZW','hide');">%s</li>"""
    
    sql_gs = """SELECT GS FROM T_BMRY GROUP BY GS"""
    sql_bm = """SELECT BM FROM T_BMRY GROUP BY BM"""
    sql_zw = """SELECT ZW FROM T_BMRY GROUP BY ZW"""
    
    dataList_gs = ms.ExecQuery(sql_gs)
    dataList_bm = ms.ExecQuery(sql_bm)
    dataList_zw = ms.ExecQuery(sql_zw)
    
    info_gs = info_bm = info_zw = ''
    if dataList_gs:
        for gs in dataList_gs:
            info_gs += li_gs % gs[0]
    if dataList_bm:
        for bm in dataList_bm:
            info_bm += li_bm % bm[0]
    if dataList_zw:
        for zw in dataList_zw:
            info_zw += li_zw % zw[0]
    @cherrypy.expose
    def index(self):
        sql = """
        SELECT * FROM T_BMRY
        ORDER BY ID
        """
        
        dataList = ms.ExecQuery(sql)
        
        _mid = ''
        i = 0
        for ry in dataList:
            i = i + 1
            _mid = _mid + self._mid_init % (i,'1',ry[0],ry[1],ry[2],4,ry[3],5,ry[4],6,ry[5])

        user = cherrypy.session.get('user')
        if user == 'admin':
            return utf8code(head() % '组织架构' + menu() + _js + _js_showInfo + _top % (self.info_gs,self.info_bm,self.info_zw) + _mid + _end + div_xxtj % (user,len(dataList)) + end())
        else:
            return utf8code(head() % '组织架构' + menu() + _js + _js_showInfo + _js_noadmin + _top % (self.info_gs,self.info_bm,self.info_zw) + _mid + _end + div_xxtj % (user,len(dataList)) + end())

    
    @cherrypy.expose
    def delRY(self,rybh):#添加一个检查，该设备已产生记录的将不能删除
        sql_check = """
            SELECT * FROM T_SBBG
            WHERE RYID = '%s'
        """
        if ms.ExecQuery(sql_check % rybh):
            return "no"
        else:
            sql = "DELETE FROM T_BMRY WHERE ID = '%s'" % rybh
            ms.ExecNonQuery(sql)
            return "ok"

    @cherrypy.expose
    def updateRY(self,rybh,zw,xm,bz):#更新人员
        try:
            sql_upt = "UPDATE T_BMRY SET ZW='%s',RY='%s',BZ='%s' WHERE ID='%s'" % (zw,xm,bz,rybh)
            print sql_upt
            ms.ExecNonQuery(sql_upt)
        except:
            return 'no'
        else:
            return 'ok'

    @cherrypy.expose
    def serchRY(self,cxtj,selradio=None):
        sql = """
            SELECT * FROM T_BMRY
            WHERE GS LIKE '%""" + cxtj + "%' OR " \
                + "BM LIKE '%" + cxtj + "%' OR " \
                + "ZW LIKE '%" + cxtj + "%' OR " \
                + "RY LIKE '%" + cxtj + "%' OR " \
                + "BZ LIKE '%" + cxtj + "%' " \
                + 'ORDER BY ID'
        dataList = ms.ExecQuery(sql)
        
        _mid = ''
        i = 0
        for ry in dataList:
            i = i + 1
            _mid = _mid + self._mid_init % (i,'1',ry[0],ry[1],ry[2],4,ry[3],5,ry[4],6,ry[5])

        user = cherrypy.session.get('user')
        if user == 'admin':
            return utf8code(head() % '组织架构' + menu() + _js + _js_showInfo + _top % (self.info_gs,self.info_bm,self.info_zw) + _mid + _end + div_xxtj % (user,len(dataList)) + end())
        else:
            return utf8code(head() % '组织架构' + menu() + _js + _js_showInfo + _js_noadmin + _top % (self.info_gs,self.info_bm,self.info_zw) + _mid + _end + div_xxtj % (user,len(dataList)) + end())
		
    @cherrypy.expose
    def saveRY(self,gs,bm,zw,ry,bz):#保存人员的时候，注意同姓名的人员给个提示，加个标记
        if (len(gs) > 0) and (len(bm) > 0) and (len(zw) > 0) and (len(ry) > 0):
            sql_checkxm = """
                SELECT RY
                FROM T_BMRY 
                WHERE GS = '%s' AND BM = '%s' AND RY = '%s'
            """  % (gs,bm,ry)
            if ms.ExecQuery(sql_checkxm):#查询有返回结果，即表示有相同姓名的人，给于提示加注标识
                return '该部门下有与此人同名的人员，请在姓名后加注标识：如XXX1，XXX2。'
            else:#无同姓名的继续添加
                sql_add = "EXECUTE PRC_ADD_BMRY '%s','%s','%s','%s','%s'" % (gs,bm,zw,ry,bz)
                print sql_add
                ms.ExecNonQuery(sql_add)
                return '保存成功!*^_^*'
        else:
            return '除"备注"外,其余四项为必填!'
    
    @cherrypy.expose
    def outRY(self):
        sql = """
                SELECT * FROM T_BMRY
                ORDER BY ID;
            """
        
        dataList = ms.ExecQuery(sql)
        
        ryxx = ''
        for ry in dataList:
            ryxx += ry[0] + "," + ry[1] + "," + ry[2] + "," + ry[3] + "," + ry[4] + "," + ry[5] + "\n"
        outFileName = "RYXX" + datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d%H%I%M%S') +".csv"
        outFile=open(os.path.join(os.getcwd(),'csv',outFileName),"w")
        outFile.write(ryxx)
        outFile.close()
        return print_head % ("操作提示","导出成功!*^_^*") + """<body onLoad='javascript:setTimeout("exit()",10000);'>""" + "<a title='人员信息下载' href='../csv/" + outFileName + "'>" + outFileName + "</a>,正在关闭此页,请稍等......</body>" + print_end